﻿using System;
using System.Collections.Generic;
using System.Text;
using ST.Model;
using System.Data;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;

namespace ST.Dal
{
    public class CategoryDal:AbstractDatabase<Category>
    {
        public override string TableName
        {
            get { return "Category"; }
        }

        public override string PrimaryKey
        {
            get { return "CategoryID"; }
        }

        public override string Fields
        {
            get { return "CategoryID,CategoryName,ParentID,OrderIndex"; }
        }

        public override Category PopulateObject(IDataReader reader)
        {
            Category category = new Category();
            category.CategoryID = (int)reader["CategoryID"];
            category.CategoryName = reader["CategoryName"].ToString();
            category.ParentID = reader["ParentID"] is DBNull?0: (int)reader["ParentID"];
            category.OrderIndex = (int)reader["OrderIndex"];
            return category;
        }
        public int CreateCategory(Category category)
        {
            if (category == null)
                throw new ArgumentNullException("create category","create category is null,please contact administrator");
            Database db = CreateDatebase();
            DbCommand command = db.GetSqlStringCommand(BuildInsertString("CategoryName","ParentID","OrderIndex"));
            db.AddInParameter(command, "@CategoryName", DbType.String, category.CategoryName);
            if (category.ParentID > 0)
                db.AddInParameter(command, "@ParentID", DbType.Int32, category.ParentID);
            else
                db.AddInParameter(command, "@ParentID", DbType.Int32, DBNull.Value);
            db.AddInParameter(command, "@OrderIndex", DbType.Int32, category.OrderIndex);
            return command.ExecuteNonQuery();
        }
        public bool UpdateCategory(Category category)
        {
            if (category == null)
                throw new ArgumentNullException("update category", "create category is null,please contact administrator");
            Database db = CreateDatebase();
            DbCommand command = db.GetSqlStringCommand(BuildUpdateString("CategoryName", "ParentID", "OrderIndex"));
            db.AddInParameter(command, "@CategoryName", DbType.String, category.CategoryName);
            if (category.ParentID > 0)
                db.AddInParameter(command, "@ParentID", DbType.Int32, category.ParentID);
            else
                db.AddInParameter(command, "@ParentID", DbType.Int32, DBNull.Value);
            db.AddInParameter(command, "@OrderIndex", DbType.Int32, category.OrderIndex);
            db.AddInParameter(command, "@CategoryID", DbType.Int32, category.CategoryID);
            return command.ExecuteNonQuery() > 0;
        }
    }
}
